package hz;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class RoomService {
	private static String url = "jdbc:mysql://localhost:3306/cs656";
	private static String username = "root";
	private static String password = "river0822";
	private static StringBuilder sb = new StringBuilder();

	static {
		sb.append(url).append('?').append("user=").append(username)
				.append("&password=").append(password);
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	static int createRoom(int aid) {

		// id, whattime, aid, bid, awin
		try (Connection conn = DriverManager.getConnection(sb.toString());
				PreparedStatement stat = conn.prepareStatement(
						"insert into games values (null, ?, ?, null, 0)",
						Statement.RETURN_GENERATED_KEYS);) {
			stat.setLong(1, System.currentTimeMillis());
			stat.setInt(2, aid);
			stat.executeUpdate();
			ResultSet generatedKeys = stat.getGeneratedKeys();
			if (generatedKeys.next())
				return generatedKeys.getInt(1);

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return 0;

	}

	static void joinRoom(int bid, int roomid) {
		try (Connection conn = DriverManager.getConnection(sb.toString());
				PreparedStatement stat = conn
						.prepareStatement("update games set bid = ? where id = ?");) {
			stat.setInt(1, bid);
			stat.setLong(2, roomid);
			stat.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	static void leaveRoom(int roomid, byte awin) {
		try (Connection conn = DriverManager.getConnection(sb.toString());
				PreparedStatement stat = conn
						.prepareStatement("update games set awin = ? where id = ?");) {
			stat.setInt(1, awin);
			stat.setLong(2, roomid);
			stat.executeUpdate();

		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	static User refreshUser(String userid, String passwd) {

		User newUser = new User();
		ResultSet rs = null;
		try (Connection conn = DriverManager.getConnection(sb.toString());
				PreparedStatement stat = conn
						.prepareStatement("select * from users where userid = ? and passwd = ?");) {
			stat.setString(1, userid);
			stat.setString(2, passwd);
			rs = stat.executeQuery();

			if (rs.next()) {
				newUser.setId(rs.getLong("id"));
				newUser.setUserid(rs.getString("userid"));
				newUser.setPasswd(rs.getString("passwd"));
				newUser.setScore(rs.getInt("score"));
				newUser.setRanking(-1);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null)
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}

		return newUser;
	}
}
